﻿using System;
using System.Web.Mvc;
using MongoDB.Bson;


namespace Nop.Web.Framework.Mvc
{
    public class NopModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var model = base.BindModel(controllerContext, bindingContext);
            if (model is BaseNopModel)
            {
                ((BaseNopModel)model).BindModel(controllerContext, bindingContext);
            }

          
            return model;
        }

        protected override System.ComponentModel.PropertyDescriptorCollection GetModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            bindingContext.PropertyFilter = new System.Predicate<string>(pred);
            var values = base.GetModelProperties(controllerContext, bindingContext);
            return values;
        }

        protected bool pred(string target)
        {
            return true;
        }
    }

    //add buy wzx
    //see:http://www.joe-stevens.com/2011/06/12/model-binding-mongodb-objectid-with-asp-net-mvc/
    public class ObjectIdBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
             var modelBinder = new DefaultModelBinder();
             var BaseNopEntityModel = modelBinder.BindModel(controllerContext, bindingContext) as BaseNopEntityModel;
        var _id = controllerContext.HttpContext.Request.Form["_id"];
        if (BaseNopEntityModel != null)
        {
            BaseNopEntityModel._id = new ObjectId(_id);
            return BaseNopEntityModel;
        }

        return null;


        //var model = base.BindModel(controllerContext, bindingContext);

        //if (model is ModelBase)
        //{
        //    ((ModelBase)model).BindModel(controllerContext, bindingContext);
        //}

        //return model;

            //var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            //result.AttemptedValue
            //return new ObjectId(result.AttemptedValue);
        }
    }
}
